﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.EventBus.Distributed;
using Volo.Abp.Identity;
using Volo.Abp.ObjectMapping;
using WMSSystem.DYB.Dto.Department;
using WMSSystem.DYB.Dto.User;
using WMSSystem.DYB.Dto.WarehouseManagement;
using WMSSystem.DYB.Dto.WarehouseManagement.Input;
using WMSSystem.DYB.Dto.WarehouseManagement.Output;
using WMSSystem.DYB.Interface;
using WMSSystem.YSL.Interfance;

namespace WMSSystem.DYB.Application
{
    public class WarehouseManagementAppService:ApplicationService, ITransientDependency,IWarehouseManagementAppService
    {
        private readonly IRepository<WarehouseManagement,Guid> _warehouserepository;
        private readonly IRepository<Department, Guid> _departmentrepository;
        private readonly IRepository<IdentityUser, Guid> _userrepository;
        private readonly ICodeRuleAppService _codeRuleAppService;
        private readonly IDistributedEventBus _distributedEventBus;
        public WarehouseManagementAppService(IRepository<WarehouseManagement, Guid> warehouserepository, IRepository<Department, Guid> departmentrepository, IRepository<IdentityUser, Guid> userrepository, ICodeRuleAppService codeRuleAppService, IDistributedEventBus distributedEventBus)
        {
            _warehouserepository = warehouserepository;
            _departmentrepository = departmentrepository;
            _userrepository = userrepository;
            _codeRuleAppService = codeRuleAppService;
            _distributedEventBus = distributedEventBus;
        }
        /// <summary>
        /// 新建部门数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<CreateDepartmentDto> CreateDepartmentAsync(CreateDepartmentDto input)
        {
            var department = ObjectMapper.Map<CreateDepartmentDto, Department>(input);
            await _departmentrepository.InsertAsync(department);
            return ObjectMapper.Map<Department, CreateDepartmentDto>(department); ;
        }
        /// <summary>
        /// 新建仓库数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<CreateWarehouseOutput> CreateWarehouseAsync(CreateWarehouseDto input)
        {
            var output = ObjectMapper.Map<CreateWarehouseDto, CreateWarehouseOutput>(input);
            var warehouse = ObjectMapper.Map<CreateWarehouseDto, WarehouseManagement>(input);
            warehouse.Code = await _codeRuleAppService.GenerateCodeAsync("warehouse");
            warehouse.CreatorId = new Guid("3a1b4d19-6f9c-7e5e-9f1f-ce1da55e4f1e");
            warehouse.Num = 0;
            warehouse.LastModificationTime = DateTime.Now;
            warehouse.UseCapacity = 0;
            warehouse.LastModifierId = new Guid("3a1b4d19-6f9c-7e5e-9f1f-ce1da55e4f1e");
            await _warehouserepository.InsertAsync(warehouse);
            return output;
        }
        /// <summary>
        /// 删除仓库
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<string> DeleteWarehouseAsync(string code)
        {
            Expression<Func<WarehouseManagement, bool>> expression = x=>x.Code== code;
            await _warehouserepository.DeleteAsync(expression);
            return code;
        }

        /// <summary>
        /// 获取部门表
        /// </summary>
        /// <returns></returns>
        public async Task<List<GetDepartmentListDto>> GetDepartmentListAsync()
        {
            var departments = await _departmentrepository.GetQueryableAsync();
            var output = ObjectMapper.Map<List<Department>,List<GetDepartmentListDto>>(departments.ToList());
            return output;
        }
        /// <summary>
        /// 获取用户表
        /// </summary>
        /// <returns></returns>
        public async Task<List<GetUserListDto>> GetUserLilstAsync()
        {
            var users = await _userrepository.GetQueryableAsync();
            var output = ObjectMapper.Map<List<IdentityUser>, List<GetUserListDto>>(users.ToList());
            return output;
        }
        /// <summary>
        /// 根据编号获取仓库信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<UpdateWarehouseInput> GetWarehouseAsync(string code)
        {
            var warehouse = await _warehouserepository.GetAsync(x=>x.Code== code);
            var output = ObjectMapper.Map<WarehouseManagement, UpdateWarehouseInput>(warehouse);
            return output;
        }

        /// <summary>
        /// 获取仓库表
        /// </summary>
        /// <returns></returns>
        public async Task<List<GetWarehouseListDto>> GetWarehouseListAsync()
        {
            var warehouses = await _warehouserepository.GetQueryableAsync();
            var departments = await _departmentrepository.GetQueryableAsync();
            var users = await _userrepository.GetQueryableAsync();
            var warehousedtos = from a in warehouses
                                join b in departments on a.DepartmentId equals b.Id
                                join c in users on a.WarehouseSupervisorId equals c.Id
                                select new GetWarehouseListDto
                                {
                                    Id = a.Id,
                                    Addr = a.Addr,
                                    State = a.State,
                                    Capacity = a.Capacity,
                                    Code = a.Code,
                                    Name = a.Name,
                                    Num = a.Num,
                                    Type = a.Type,
                                    LastModificationTime = a.LastModificationTime,
                                    DepartmentName = b.Name,
                                    WarehouseSupervisorName = c.UserName,
                                    LastModifierName = "admin"
                                };
            return warehousedtos.ToList();
        }
        /// <summary>
        /// 根据编码获取仓库详细信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<GetWarehouseOutput> GetWarehouseOutputAsync(Guid Id)
        {
            var warehouse = await _warehouserepository.GetAsync(Id);
            var users = await _userrepository.GetAsync(warehouse.WarehouseSupervisorId);
            var departs = await _departmentrepository.GetAsync(warehouse.DepartmentId);
            Expression<Func<IdentityUser, bool>> expression = x => x.Id == warehouse.CreatorId;
            GetWarehouseOutput output = ObjectMapper.Map<WarehouseManagement, GetWarehouseOutput>(warehouse);
            output.WarehouseSupervisorName = users.UserName;
            output.CreatorName = "admin";
            output.DepartmentName = departs.Name;
            output.LastModifierName = "admin";
            return output;
        }

        /// <summary>
        /// 修改仓库
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<UpdateWarehouseInput> UpdateWarehouseAsync(UpdateWarehouseInput input)
        {
            var warehouse = await _warehouserepository.GetAsync(x => x.Code == input.Code);
            if (warehouse == null)
            {
                return new UpdateWarehouseInput();
            }

            // 只更新需要的字段
            warehouse.Name = input.Name;
            warehouse.Capacity = input.Capacity;
            warehouse.Addr = input.Addr;
            warehouse.DepartmentId = input.DepartmentId;
            warehouse.WarehouseSupervisorId = input.WarehouseSupervisorId;
            warehouse.State = input.State;
            warehouse.LockState = input.LockState;
            warehouse.Remark = input.Remark;
            warehouse.Phone = input.Phone;
            warehouse.Type = input.Type;
            warehouse.LastModificationTime = DateTime.Now;
            warehouse.LastModifierId = new Guid("3a1b4d19-6f9c-7e5e-9f1f-ce1da55e4f1e"); // 强制赋值
            // 其它业务字段可按需补充

            await _warehouserepository.UpdateAsync(warehouse);

            return input;
        }
    }
}
